var express = require("express");
var router = express.Router();
var collectInfoService = require("../../service/blog/collectInfoService");
const authMiddleware = require("../../middleware/authMiddleware");
var mongoose = require("mongoose");
//列表
router.get(
    "/list",
    async (req, res, next) => {
        console.log("====================================================")
        let list = await collectInfoService.query(req.query);
        res.json({ code: 1, data: list });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//新增
router.post(
    "/add",
    authMiddleware.verifyToken,
    async (req, res, next) => {
        collectInfoService.add({
            ...req.body,
            readNum: 0,
        }).then(() => {
            res.json({ code: 1, msg: "新增成功" });
        });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//更新
router.post(
    "/update",
    authMiddleware.verifyToken,
    async (req, res, next) => {
        collectInfoService.update(req.body).then(() => {
            res.json({ code: 1, msg: "更新成功" });
        });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//删除
router.post(
    "/remove",
    authMiddleware.verifyToken,
    async (req, res, next) => {
        let { _id } = req.body;
        if (!mongoose.Types.ObjectId.isValid(_id)) return res.json({ code: 0, msg: `_id查询失败：${_id}` });
        // if (_id == "" || !_id) return res.json({ code: 0, msg: "_id不存在" });
        collectInfoService.delete({ _id: _id }).then(() => {
            res.json({ code: 1, msg: "删除成功" });
        });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);
//查询
router.get(
    "/model",
    async (req, res, next) => {
        let { _id } = req.query;
        if (!mongoose.Types.ObjectId.isValid(_id)) return res.json({ code: 0, msg: `_id查询失败：${_id}` });
        let list = await collectInfoService.query({ _id });
        res.json({ code: 1, data: list.length > 0 ? list[0] : {} });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);

//点击分享
router.post(
    "/readCollect",
    async (req, res, next) => {
        let { _id } = req.body;
        let list = await collectInfoService.query({ _id })
        let readNum = 0
        if (list.length > 0) { readNum = list[0].readNum += 1 }
        collectInfoService
            .updateRedNum({ _id, readNum })
            .then(() => { res.json({ code: 1, msg: "更新成功" }) });
    },
    (err) => {
        res.json({ code: 0, msg: err });
    }
);

module.exports = router;
